package com.hj.monitor.sdk.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.hj.monitor.sdk.model.LogMessage;
import com.hj.monitor.sdk.push.IPush;
import com.hj.monitor.sdk.push.impl.RedisPush;

import java.util.Arrays;

/**
 * 自定义附加程序
 *
 * @author 黄健
 * @date 2024/12/03
 */
public class CustomAppender<E> extends AppenderBase<E> {

    // 系统名称
    private String systemName;
    // 只采集指定范围的日志
    private String groupId;
    /**
     * 主机
     */
    private String host;


    /**
     * 端口
     */
    private int port;

    /**
     * 推送
     */
    private final IPush push = new RedisPush();


    /**
     * 附加
     *
     * @param eventObject 事件对象
     */
    @Override
    protected void append(E eventObject) {
        // 开启推送
        push.open(host, port);
        // 获取日志
        if (eventObject instanceof ILoggingEvent) {
            ILoggingEvent event = (ILoggingEvent) eventObject;

            String methodName = "unknown";
            String className = "unknown";

            StackTraceElement[] callerDataArray = event.getCallerData();
            if (null != callerDataArray && callerDataArray.length > 0) {
                StackTraceElement callerData = callerDataArray[0];
                methodName = callerData.getMethodName();
                className = callerData.getClassName();
            }

            if (!className.startsWith(groupId)){
                return;
            }

            // 构建日志
            LogMessage logMessage = new LogMessage(systemName, className, methodName, Arrays.asList(event.getFormattedMessage().split(" ")));
            // 推送日志
            push.send(logMessage);
        }
    }


    /**
     * 获取系统名称
     *
     * @return
     */
    public String getSystemName() {
        return systemName;
    }

    /**
     * Sets system name.
     *
     * @param systemName the system name
     */
    public void setSystemName(String systemName) {
        this.systemName = systemName;
    }

    /**
     * Gets group id.
     *
     * @return the group id
     */
    public String getGroupId() {
        return groupId;
    }

    /**
     * Sets group id.
     *
     * @param groupId the group id
     */
    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    /**
     * Gets host.
     *
     * @return the host
     */
    public String getHost() {
        return host;
    }

    /**
     * Sets host.
     *
     * @param host the host
     */
    public void setHost(String host) {
        this.host = host;
    }

    /**
     * Gets port.
     *
     * @return the port
     */
    public int getPort() {
        return port;
    }

    /**
     * Sets port.
     *
     * @param port the port
     */
    public void setPort(int port) {
        this.port = port;
    }



}
